package com.tengju.bff.interfaces.manage.platform.rule.assembler;

import com.beust.jcommander.internal.Lists;
import com.tengju.bff.interfaces.manage.platform.rule.form.ActionVO;
import com.tengju.bff.interfaces.manage.platform.rule.form.EditFullMatchRuleVO;
import com.tengju.bff.interfaces.manage.platform.rule.form.FullMatchRuleNodeVO;
import com.tengju.bff.interfaces.manage.platform.rule.form.FullMatchRuleVO;
import com.tengju.support.domain.model.rule.*;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

public class RuleAssembler {

    public static FullMatchRuleForm toModel(EditFullMatchRuleVO editFullMatchRuleVO) {

        FullMatchRuleVO fullMatchRuleVO = editFullMatchRuleVO.getFullMatchRuleVO();

        return toModel(fullMatchRuleVO);

    }


    public static FullMatchRuleForm toModel(FullMatchRuleVO fullMatchRuleVO) {

        List<FullMatchRuleNodeForm> fullMatchRuleNodeForms = Lists.newArrayList();
        List<FullMatchRuleNodeVO> nodes = fullMatchRuleVO.getNodes();

        for (FullMatchRuleNodeVO node : nodes) {

            List<ConditionForm> conditionForms = node.getConditions().stream().map(conditionVO -> new ConditionForm(conditionVO.getField(),
                    Operation.parseByVal(conditionVO.getOperation()),
                    conditionVO.getFactors())).collect(Collectors.toList());

            List<ActionForm> actionForms = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(node.getActions())) {
                actionForms = node.getActions().stream()
                        .map(RuleAssembler::createActionForm).collect(Collectors.toList());
            }

            FullMatchRuleNodeForm nodeForm =
                    new FullMatchRuleNodeForm(conditionForms, actionForms);

            fullMatchRuleNodeForms.add(nodeForm);
        }

        return new FullMatchRuleForm(BizType.fromVal(fullMatchRuleVO.getBizType()),
                fullMatchRuleVO.getRuleDesc(),
                fullMatchRuleNodeForms);

    }

    private static ActionForm createActionForm(ActionVO actionVO) {

        return new ActionForm(
                ActionType.fromVal(actionVO.getActionType()),
                actionVO.getActionInfo()
        );

    }


}
